<template>
  <!-- 设备管理页面容器 -->
  <div class="equipment-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">设备管理</h2>
      <div class="breadcrumb">首页 / 医生工作台 / 基础设置 / 设备管理</div>
    </div>

    <!-- 搜索过滤卡片 -->
    <div class="search-card">
      <div class="search-form">
        <div class="search-item">
          <label class="search-label">设备名称</label>
          <el-input 
            v-model="Query.EquipmentName" 
            placeholder="请输入设备名称" 
            class="input-search"
            prefix-icon="el-icon-search"
            clearable 
          />
        </div>
        
        <div class="search-actions">
          <el-button 
            @click="equiplist"
            class="search-btn"
          >
            <i class="el-icon-search"></i>
            查询
          </el-button>
          <el-button 
            @click="resetSearch"
            class="reset-btn"
          >
            <i class="el-icon-refresh"></i>
            重置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 设备操作与表格区域 -->
    <div class="equipment-content">
      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <el-button 
          @click="equipadddata(null)"
          class="add-btn"
        >
          <i class="el-icon-plus"></i>
          新增设备
        </el-button>
        <el-button 
          class="enable-btn"
        >
          <i class="el-icon-check"></i>
          启用
        </el-button>
        <el-button 
          class="disable-btn"
        >
          <i class="el-icon-pause"></i>
          停用
        </el-button>
        <el-button 
          class="delete-btn"
        >
          <i class="el-icon-delete"></i>
          删除
        </el-button>
      </div>

      <!-- 设备表格 -->
      <div class="table-container">
        <el-table 
          :data="equipdata" 
          style="width: 100%"
          :row-class-name="tableRowClassName"
          empty-text="暂无数据"
          :header-cell-style="headerCellStyle"
        >
          <el-table-column prop="equipmentCoding" label="设备编码" width="150" />
          <el-table-column prop="equipmentName" label="设备名称" min-width="200" />
          <el-table-column prop="equipmentBrand" label="品牌" width="120" />
          <el-table-column prop="equipmentType" label="型号" width="150" />
          <el-table-column prop="equipmentSNnum" label="设备SN号" width="180" />
          <el-table-column prop="equipmentStatus" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                :type="scope.row.equipmentStatus ? 'primary' : 'warning'"
                effect="light"
              >
                {{ scope.row.equipmentStatus ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                size="small" 
                @click="equipadddata(scope.row)"
                class="edit-link"
              >
                编辑
              </el-button>
              <el-button 
                link 
                type="danger" 
                size="small"
                @click="open(scope.row.equipmentId)"
                class="delete-link"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pagindex"
          v-model:page-size="page.pagsize"
          :page-sizes="[5, 10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalcount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 设备编辑弹窗 -->
    <el-dialog 
      v-model="teamSettinig.isOpen" 
      :title="teamSettinig.title" 
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="equipadd" class="dialog-form">
        <el-form-item label="设备品牌:" :required="true">
          <el-select 
            v-model="equipadd.equipmentBrand" 
            placeholder="请选择" 
            style="width: 100%"
          >
            <el-option label="霍尼韦尔" value="霍尼韦尔" />
            <el-option label="美敦力" value="美敦力" />
            <el-option label="强生" value="强生" />
            <el-option label="西门子" value="西门子" />
            <el-option label="罗氏诊断" value="罗氏诊断" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编码:" :required="true">
          <el-input v-model="equipadd.equipmentCoding" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备名称:" :required="true">
          <el-input v-model="equipadd.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备型号:" :required="true">
          <el-input v-model="equipadd.equipmentType" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备SN号:" :required="true">
          <el-input v-model="equipadd.equipmentSNnum" placeholder="请输入设备SN号" />
        </el-form-item>
        <el-form-item label="状态:" :required="true">
          <el-switch v-model="equipadd.equipmentStatus" active-text="启用" inactive-text="停用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="teamSettinig.isOpen = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="set" class="save-btn">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'

// 定义设备数据接口
interface EquipmentData {
  equipmentId: number | string
  equipmentBrand: string
  equipmentName: string
  equipmentCoding: string
  equipmentType: string
  equipmentSNnum: string
  equipmentStatus: boolean
  isDelete?: boolean
  createdTime?: string
}

// 定义查询参数接口
interface QueryParams {
  EquipmentName: string
}

// 定义分页参数接口
interface PageParams {
  pagindex: number
  pagsize: number
  totalcount: number
  totalpage: number
}

// 初始化 store
const store = useCounterStore()

// 查询参数
const Query = reactive<QueryParams>({
  EquipmentName: "",
})

// 分页参数
const page = reactive<PageParams>({
  pagindex: 1,
  pagsize: 10,
  totalcount: 0,
  totalpage: 1,
})

// 设备数据
const equipdata = ref<EquipmentData[]>([])

// 弹窗设置
const teamSettinig = reactive({
  isOpen: false,
  title: "",
  isbool: false
})

// 表单数据
const equipadd = reactive<EquipmentData>({
  "equipmentId": 0,
  "equipmentBrand": "",
  "equipmentName": "",
  "equipmentCoding": "",
  "equipmentType": "",
  "equipmentSNnum": "",
  "equipmentStatus": true,
  "isDelete": false,
  "createdTime": new Date().toISOString()
})

// 表格头部样式
const headerCellStyle = {
  backgroundColor: '#f0f8ff',
  fontWeight: 600,
  color: '#003d79',
  textAlign: 'center'
}

// 表格行样式
const tableRowClassName = ({ rowIndex }: { rowIndex: number }): string => {
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd'
}

// 获取设备数据
const equiplist = async (): Promise<void> => {
  try {
    const response = await axios.get("http://localhost:5108/api/Manager/EquipmentShow", {
      params: {
        EquipmentName: Query.EquipmentName,
        pagindex: page.pagindex,
        pagsize: page.pagsize
      }
    })
    
    // 添加安全检查
    if (response.data && response.data.data) {
      equipdata.value = response.data.data.data || []
      page.totalcount = response.data.data.totalCount || 0
      page.totalpage = response.data.data.totalPage || 0
    } else {
      // 使用模拟数据
      getMockData()
    }
  } catch (error) {
    console.error('获取设备数据失败:', error)
    // 如果API失败，使用模拟数据
    getMockData()
  }
}

// 获取模拟数据
const getMockData = (): void => {
  equipdata.value = [
    {
      equipmentId: 1,
      equipmentBrand: "西门子",
      equipmentName: "血压监测仪",
      equipmentCoding: "BP-2024-001",
      equipmentType: "Siemens BP200",
      equipmentSNnum: "SN-BP001-2024",
      equipmentStatus: true,
      isDelete: false,
      createdTime: "2024-01-15T08:30:00Z"
    },
    {
      equipmentId: 2,
      equipmentBrand: "美敦力",
      equipmentName: "血糖仪",
      equipmentCoding: "GLU-2024-001",
      equipmentType: "Medtronic Guardian",
      equipmentSNnum: "SN-GLU001-2024",
      equipmentStatus: true,
      isDelete: false,
      createdTime: "2024-01-20T10:15:00Z"
    },
    {
      equipmentId: 3,
      equipmentBrand: "罗氏诊断",
      equipmentName: "心电监测仪",
      equipmentCoding: "ECG-2024-001",
      equipmentType: "Roche CardioPro",
      equipmentSNnum: "SN-ECG001-2024",
      equipmentStatus: false,
      isDelete: false,
      createdTime: "2024-02-05T14:20:00Z"
    },
    {
      equipmentId: 4,
      equipmentBrand: "强生",
      equipmentName: "体重秤",
      equipmentCoding: "WT-2024-001",
      equipmentType: "Johnson HealthScale",
      equipmentSNnum: "SN-WT001-2024",
      equipmentStatus: true,
      isDelete: false,
      createdTime: "2024-02-15T09:45:00Z"
    },
    {
      equipmentId: 5,
      equipmentBrand: "霍尼韦尔",
      equipmentName: "血氧仪",
      equipmentCoding: "SPO2-2024-001",
      equipmentType: "Honeywell PulseOx",
      equipmentSNnum: "SN-SPO2001-2024",
      equipmentStatus: true,
      isDelete: false,
      createdTime: "2024-03-01T11:30:00Z"
    }
  ]
  page.totalcount = equipdata.value.length
  page.totalpage = Math.ceil(page.totalcount / page.pagsize)
}

// 重置搜索
const resetSearch = (): void => {
  Query.EquipmentName = ""
  page.pagindex = 1
  equiplist()
}

// 处理编辑/新增
const equipadddata = (t: EquipmentData | null): void => {
  teamSettinig.isOpen = true
  if (t === null) {
    teamSettinig.title = "新增设备"
    teamSettinig.isbool = true
    // 重置表单
    equipadd.equipmentId = 0
    equipadd.equipmentBrand = ""
    equipadd.equipmentName = ""
    equipadd.equipmentCoding = ""
    equipadd.equipmentType = ""
    equipadd.equipmentSNnum = ""
    equipadd.equipmentStatus = true
  } else {
    teamSettinig.title = "修改设备"
    teamSettinig.isbool = false
    // 填充表单数据
    Object.assign(equipadd, t)
  }
}

// 保存数据
const set = async (): Promise<void> => {
  // 简单验证
  if (!equipadd.equipmentName || !equipadd.equipmentCoding || !equipadd.equipmentBrand) {
    ElMessage.warning('请填写必要的设备信息')
    return
  }
  
  try {
    if (teamSettinig.isbool) {
      // 新增设备
      const response = await axios.post("http://localhost:5203/api/Managment/AddEquipment", equipadd)
      if (response.data?.code === 1) {
        ElMessage.success('新增成功')
        teamSettinig.isOpen = false
        equiplist()
      }
    } else {
      // 修改设备
      const response = await axios.put("http://localhost:5203/api/Managment/EquipmentTableUpdate", equipadd)
      if (response.data?.code === 1) {
        ElMessage.success('修改成功')
        teamSettinig.isOpen = false
        equiplist()
      }
    }
  } catch (error) {
    console.error('保存设备信息失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 处理分页大小变化
const handleSizeChange = (size: number): void => {
  page.pagsize = size
  equiplist()
}

// 处理页码变化
const handleCurrentChange = (current: number): void => {
  page.pagindex = current
  equiplist()
}

// 逻辑删除方法
const open = (equipmentId: number | string): void => {
  ElMessageBox.confirm(
    '您确定要删除该设备吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const response = await axios.delete("http://localhost:5203/api/Managment/EquipmentTableDelete", {
          data: {
            equipmentId: equipmentId
          }
        })
        if (response.data?.code === 1) {
          ElMessage.success('删除成功')
          equiplist()
        }
      } catch (error) {
        console.error('删除设备失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    })
}

// 钩子函数
onMounted(() => {
  equiplist()
})

// 侦听器
watch(page, () => {
  // 避免重复调用
}, { deep: true })
</script>
<style scoped>
/* 现代医疗系统设计风格 - 专业医疗蓝主题 */

/* 页面主容器 */
.equipment-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f2ff 100%);
  min-height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 页面标题区域 - 玻璃拟态效果 */
.page-header {
  margin-bottom: 28px;
  padding: 20px 28px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(12px);
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #003d79;
}

.breadcrumb {
  font-size: 14px;
  color: #64748b;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 123, 255, 0.1);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 20px rgba(0, 123, 255, 0.15);
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-label {
  font-weight: 500;
  color: #334155;
  white-space: nowrap;
}

.input-search {
  width: 280px;
}

.search-actions {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

/* 按钮样式 */
.search-btn, .reset-btn, .add-btn, .enable-btn, .disable-btn, .delete-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-btn {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border: none;
  color: white;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}

.reset-btn {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #495057;
}

.reset-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

/* 设备内容区域 */
.equipment-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 123, 255, 0.1);
  margin-bottom: 24px;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.add-btn {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border: none;
  color: white;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}

.enable-btn {
  background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
  border: none;
  color: white;
}

.enable-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}

.disable-btn {
  background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
  border: none;
  color: white;
}

.disable-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 193, 7, 0.3);
}

.delete-btn {
  background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
  border: none;
  color: white;
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

/* 表格样式 */
.table-container {
  margin-bottom: 24px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f2ff 100%);
}

.el-table__row:hover {
  background-color: #f0f9ff;
}

.table-row-even {
  background-color: #ffffff;
}

.table-row-odd {
  background-color: #f9fafb;
}

/* 链接按钮样式 */
.edit-link:hover {
  color: #007bff;
}

.delete-link:hover {
  color: #dc3545;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

/* 弹窗样式 */
.dialog-form {
  padding: 10px 0;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: 500;
  color: #374151;
}

.el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  color: white;
  padding: 20px;
  margin: 0;
}

.el-dialog__title {
  color: white;
  font-weight: 600;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  background-color: #f9fafb;
  border-top: 1px solid #e5e7eb;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  padding-top: 20px;
}

.cancel-btn, .save-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.save-btn {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border: none;
  color: white;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .equipment-container {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .equipment-container {
    padding: 16px;
  }
  
  .page-header {
    padding: 16px;
    margin-bottom: 20px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-item {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .input-search {
    width: 100%;
  }
  
  .search-actions {
    margin-left: 0;
    justify-content: center;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .action-buttons .el-button {
    flex: 1;
    min-width: 120px;
  }
  
  .pagination-container {
    justify-content: center;
  }
  
  .el-dialog {
    width: 90% !important;
    margin: 10vh auto;
  }
}
</style>